var ul = document.getElementsByTagName('ul')[0];
var li = ul.getElementsByTagName('li');
var index = 1;
var liW = li[0].offsetWidth;
ul.style.marginLeft = (-liW*index)+"px";
var pillow = document.getElementsByClassName('bearFly')[0];
var isClick = true;
var body = document.getElementsByTagName('body')[0];
var li_clone =  li[1].cloneNode(true);
ul.insertBefore(li_clone,li[0]);
var begin = ul.getElementsByClassName('open')[0];
var top_begin = parseInt(getComputedStyle(pillow).top);
var grade = document.getElementsByClassName('grade')[0];
var web = document.getElementById('web');
var again = document.getElementsByClassName('again')[0];
var end = document.getElementsByClassName('end')[0];
var open = ul.getElementsByClassName('open')[0];
var man = document.getElementById('man');
var isStart = true;
var score = 0;
var p = grade.getElementsByTagName('p')[0];

function go(num = 1){
	if(isClick){
		index += num;
		if(!ul.classList.contains("start")){
			ul.classList.add("start");
		}
		ul.style.marginLeft = -(liW +index*10)+"px";
		begin.style.left = (0 -index*10)+"px";
		pillow.style.top = oldTop() + 5 +"px";
		if(parseFloat(pillow.style.top) <= 0 ){
			pillow.style.top = oldTop() + 100 +"px";
		}
		if(parseFloat(pillow.style.top) >= top_begin){
			clearInterval(t);
			grade.style.display = 'block';
			end.style.display = 'block';
			open.style.display = 'none';
			p.innerHTML = score;
		}
	}
	score += 300;
}

function oldTop(){
	if(pillow.style.top){
		return parseInt(pillow.style.top);
	}
	else{
		return parseInt(window.getComputedStyle(pillow).top );
	}
}

var t = null;
function autoRun(){
	t = setInterval(go,100);
}
var flag = false;
web.addEventListener('touchend',function(){
	if(!flag){
		clearInterval(s);
		autoRun();
		pillow.style.top = oldTop() - 150 + 'px';
		flag = true;
	}
})

again.onclick = function(){
	window.location.href = "game.html";
}

web.addEventListener('touchstart',function(){
	if(isStart){
		var value = man.offsetLeft
		var value1 = 0;
		function loading(){
			if(value1 == 90){
				clearInterval(s);
			}
			value1 += 10; 
			value += 10;
			man.style.left = value / 100 *100 +'%'
			man.classList.add('start');
		}
		s = setInterval(loading,100)
		isStart = false;
	}else{
		if(flag == true){
			pillow.style.top = oldTop() - 50 +"px";
			man.style.left = (parseInt(man.style.left) - 10) + '%';
			console.log(man.style.left);
			if(man.style.left <= 0+'%'){
				clearInterval(t);
				grade.style.display = 'block';
				end.style.display = 'block';
				open.style.display = 'none';
				pillow.style.top = parseInt(top_begin) + 'px';
				pillow.style.left = 30 + '%';
				pillow.classList.add('start');
				p.innerHTML = score;
			}
		}
	}
})

